// wifi.c
// 用于管理wifi连接
#include "freertos/FreeRTOS.h"  // xTaskCreate
#include "esp_mac.h"  // MACSTR
#include "esp_wifi.h"  // esp_netif_init
#include "esp_err.h"  // ESP_ERROR_CHECK
#include "esp_log.h" // ESP_LOGI
#include "common.h"

// 暴露变量
TaskHandle_t wifi_handle = NULL;
// 内部变量
static const char *TAG = "WIFI";
// 设备连接/断开事件
static void wifi_event_handler(void *arg, esp_event_base_t event_base,
int32_t event_id, void *event_data) {
  if (event_id == WIFI_EVENT_AP_STACONNECTED) {  // 连入设备
    wifi_event_ap_staconnected_t *event =
      (wifi_event_ap_staconnected_t *)event_data;
    ESP_LOGI(TAG, "ADD MAC="MACSTR" AID=%d.", MAC2STR(event->mac), event->aid);
  } else if (event_id == WIFI_EVENT_AP_STADISCONNECTED) {  // 断开设备
    wifi_event_ap_stadisconnected_t *event =
      (wifi_event_ap_stadisconnected_t *)event_data;
    ESP_LOGI(TAG, "DEL MAC="MACSTR" AID=%d reason=%d.",
      MAC2STR(event->mac), event->aid, event->reason);
  } else {  // 其他事件
    ESP_LOGI(TAG, "WIFI_EVENT=%d.", event_id);
  }
}

void wifi_task(void *arg) {
  /*--------初始化--------*/
  ESP_ERROR_CHECK(esp_netif_init());  // 初始化TCP/IP协议栈
  ESP_ERROR_CHECK(esp_event_loop_create_default());  // 创建事件循环
  esp_netif_create_default_wifi_ap();  // 初始化AP接口
  ESP_LOGI(TAG, "init finish.");
  /*--------热点逻辑--------*/
  while (true) {
    xTaskNotifyWait(0, 0, NULL, portMAX_DELAY);
    ESP_LOGI(TAG, "state: %s.", switch_state == 1 ? "on" : "off");
    esp_event_handler_instance_t wifi_event_instance;  // wifi事件
    if (switch_state == 1) {  // 开
      wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();
      ESP_ERROR_CHECK(esp_wifi_init(&cfg));
      ESP_ERROR_CHECK(esp_event_handler_instance_register(WIFI_EVENT,
        ESP_EVENT_ANY_ID, &wifi_event_handler, NULL, &wifi_event_instance));
      wifi_config_t wifi_config = {
        .ap = { .ssid = "BlueRemap", .ssid_len = 9, .channel = 1,
        .max_connection = 1, .authmode = WIFI_AUTH_OPEN,},
      };
      ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_AP));
      ESP_ERROR_CHECK(esp_wifi_set_config(WIFI_IF_AP, &wifi_config));
      ESP_ERROR_CHECK(esp_wifi_start());
      ESP_LOGI(TAG, "SSID:%s.", wifi_config.ap.ssid);
      ESP_LOGI(TAG, "channel:%d.", wifi_config.ap.channel);
      ESP_LOGI(TAG, "wifi started.");
    } else {  // 关
      ESP_ERROR_CHECK(esp_event_handler_instance_unregister(WIFI_EVENT,
        ESP_EVENT_ANY_ID, wifi_event_instance));  // 注销事件
      ESP_ERROR_CHECK(esp_wifi_stop());
      ESP_ERROR_CHECK(esp_wifi_deinit());  // 释放硬件
      ESP_LOGI(TAG, "wifi stopped.");
    }
    xTaskNotify(switch_handle, 0, eNoAction);
  }
}
